package com.shengwei.truck.driver.view.ui.task;
import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonTaskDetailData;
import com.shengwei.truck.driver.databinding.ExcepTaskDetailBinding;
import com.shengwei.truck.driver.permission.RxjavaPermissionUtil;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.task.pounds.PostPoundsListActivity;
import com.shengwei.truck.driver.vm.TaskDetailViewModel;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

/**
 * 异常任务详情页,
 * 由于“任务详情页面”根据任务状态显示或隐藏的东西太多，因此给“异常任务”单独创建一个详情页面，便于维护。
 */
public class ExcepTaskDetailActivity extends BaseActivity<TaskDetailViewModel, ExcepTaskDetailBinding> implements View.OnClickListener {
    private static final String TAG = ExcepTaskDetailActivity.class.getSimpleName() ;
    private String mTaskId;
    private String mTaskNo;
    private String mUnit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initLiveDataObersve();
        getLastIntent();
        JsonTaskDetailData detailData = new JsonTaskDetailData();
        mDataBinding.setTaskDetail(detailData);
        mViewModel.getTaskDetail(mTaskId);
    }

    /**
     * 初始化控件显示
     */
    private void initView() {
        mDataBinding.contactCommonLayout.taskDetailMainLayout.setVisibility(View.VISIBLE);
        mDataBinding.btPostPoundsList.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.imvPublishPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.imvRecvPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.tvReceiverPhone.setOnClickListener(this);

        mDataBinding.contactCommonLayout.tvDispatchPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.imvDispatchPhone.setOnClickListener(this);
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听获取任务详情的数据
        mViewModel.getTaskDetailLiveData().observe(this, new Observer<Result<JsonTaskDetailData>>() {
            @Override
            public void onChanged(Result<JsonTaskDetailData> result) {
                result.handler(new OnCallback<JsonTaskDetailData>() {
                    @Override
                    public void onSuccess(JsonTaskDetailData data) {
                        mDataBinding.setTaskDetail(data);
                        if(TextUtils.isEmpty(data.factoryLinkPhone)){
                            mDataBinding.contactCommonLayout.loadUnloadAddress.imvPublishPhone.setVisibility(View.GONE);
                            mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.setVisibility(View.GONE);
                        }
                        //以下字段传递到“上传榜单”页面直接显示，这样“上传榜单”页面就不用再调取接口了。
                        mTaskId = data.id;
                        mTaskNo = data.taskNo;
                        mUnit = data.unit;
                    }
                });
            }
        });
    }

    /**
     * 获取上一页的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mTaskId = bundle.getString("id");
        }
    }
    @Override
    public int getContentViewId() {
        return R.layout.excep_task_detail;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imvPublishPhone: //派单人的电话
            case R.id.tvPublishPhone:
                String publishPhone = mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.getText().toString();
                if(!TextUtils.isEmpty(publishPhone)) {
                    callPhone(publishPhone);
                }
                break;
            case R.id.imvRecvPhone:
            case R.id.tvReceiverPhone:
                String recvPhone = mDataBinding.contactCommonLayout.loadUnloadAddress.tvReceiverPhone.getText().toString();
                if(!TextUtils.isEmpty(recvPhone)) {
                    callPhone(recvPhone);
                }
                break;
            case R.id.imvDispatchPhone:
            case R.id.tvDispatchPhone:
                String dispatchPhone = mDataBinding.contactCommonLayout.tvDispatchPhone.getText().toString();
                if(!TextUtils.isEmpty(dispatchPhone)) {
                    callPhone(dispatchPhone);
                }
                break;
            case R.id.btPostPoundsList: //上传榜单
               Intent i = new Intent(ExcepTaskDetailActivity.this, PostPoundsListActivity.class);
                i.putExtra("taskId",mTaskId);
                i.putExtra("taskNo",mTaskNo);
                i.putExtra("unit",mUnit);
                i.putExtra("fromPage",2);
                startActivity(i);
                break;
        }
    }

    /**
     * 拨打电话
     * @param phone
     */
    private void callPhone(final String phone) {

        //申请多个权限，当所有权限操作完后（批处理），才回调用accept函数，进而才能知道哪个权限被允许了，哪个权限被禁止了。
        final String[] permissionCall = {Manifest.permission.CALL_PHONE};
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.requestEach(permissionCall)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-permission-:" + permission.name + "---------------");
                        if (permission.name.equalsIgnoreCase(Manifest.permission.CALL_PHONE)) {
                            if (permission.granted) {//同意后调用
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + true);
                                Intent intent = new Intent(); // 意图对象：动作 + 数据
                                intent.setAction(Intent.ACTION_CALL); // 设置动作
                                Uri data = Uri.parse("tel:" + phone); // 设置数据
                                intent.setData(data);
                                ExcepTaskDetailActivity.this.startActivity(intent); // 激活Activity组件
                            } else if (permission.shouldShowRequestPermissionRationale){//禁止，但没有选择“以后不再询问”，以后申请权限，会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-shouldShowRequestPermissionRationale:" + false);
                            }else {//禁止，但选择“以后不再询问”，以后申请权限，不会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + false);
                                Toast.makeText(ExcepTaskDetailActivity.this, R.string.call_failed, Toast.LENGTH_SHORT).show();
                                RxjavaPermissionUtil.getInstance().alertOpenNavPermission(ExcepTaskDetailActivity.this,permissionCall);

                            }
                        }
                    }
                });
    }
}